<template>
    <view class="login-form">
        <view class="form-header">
            <view class="title">{{ mode === 'login' ? '登录' : mode === 'register' ? '注册' : '重置密码' }}</view>
            <view class="subtitle">{{ getSubtitle() }}</view>
        </view>

        <view class="form-content">
            <!-- 手机号输入 -->
            <view class="input-group">
                <view class="input-label">手机号</view>
                <view class="input-wrapper">
                    <input v-model="formData.phone" type="number" placeholder="请输入手机号" :disabled="loading" @blur="validatePhone" />
                    <u-icon v-if="formData.phone" name="close-circle-fill" size="16" color="#c8c9cc" @click="formData.phone = ''" />
                </view>
                <view v-if="errors.phone" class="error-text">{{ errors.phone }}</view>
            </view>

            <!-- 验证码输入 (注册和忘记密码时显示) -->
            <view v-if="mode !== 'login'" class="input-group">
                <view class="input-label">验证码</view>
                <view class="input-wrapper">
                    <input v-model="formData.code" type="number" placeholder="请输入验证码" :disabled="loading" />
                    <view class="code-btn" :class="{ disabled: codeDisabled }" @click="sendCode">
                        {{ codeText }}
                    </view>
                </view>
                <view v-if="errors.code" class="error-text">{{ errors.code }}</view>
            </view>

            <!-- 密码输入 -->
            <view class="input-group">
                <view class="input-label">{{ mode === 'login' ? '密码' : '新密码' }}</view>
                <view class="input-wrapper">
                    <input v-model="formData.password" :type="showPassword ? 'text' : 'password'" placeholder="请输入密码" :disabled="loading" />
                    <u-icon :name="showPassword ? 'eye' : 'eye-off'" size="16" color="#c8c9cc" @click="showPassword = !showPassword" />
                </view>
                <view v-if="errors.password" class="error-text">{{ errors.password }}</view>
            </view>

            <!-- 确认密码输入 (注册和忘记密码时显示) -->
            <view v-if="mode !== 'login'" class="input-group">
                <view class="input-label">确认密码</view>
                <view class="input-wrapper">
                    <input
                        v-model="formData.confirmPassword"
                        :type="showConfirmPassword ? 'text' : 'password'"
                        placeholder="请再次输入密码"
                        :disabled="loading"
                    />
                    <u-icon
                        :name="showConfirmPassword ? 'eye' : 'eye-off'"
                        size="16"
                        color="#c8c9cc"
                        @click="showConfirmPassword = !showConfirmPassword"
                    />
                </view>
                <view v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</view>
            </view>

            <!-- 推荐人手机号 (注册时显示) -->
            <view v-if="mode === 'register'" class="input-group">
                <view class="input-label">推荐人手机号 (可选)</view>
                <view class="input-wrapper">
                    <input v-model="formData.referrerPhone" type="number" placeholder="请输入推荐人手机号" :disabled="loading" />
                </view>
            </view>

            <!-- 提交按钮 -->
            <view class="submit-btn" :class="{ disabled: loading }" @click="handleSubmit">
                <u-loading-icon v-if="loading" mode="spinner" size="18" color="#fff" />
                <text>{{ loading ? '提交中...' : getButtonText() }}</text>
            </view>

            <!-- 切换模式 -->
            <view class="mode-switch">
                <text v-if="mode === 'login'" @click="$emit('switch-mode', 'register')">没有账号？立即注册</text>
                <text v-if="mode === 'login'" @click="$emit('switch-mode', 'forgot')">忘记密码？</text>
                <text v-if="mode !== 'login'" @click="$emit('switch-mode', 'login')">已有账号？立即登录</text>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { sendCode as sendCodeApi } from '@/api/common/common'

interface LoginFormData {
    phone: string
    code: string
    password: string
    confirmPassword: string
    referrerPhone: string
}

interface LoginProps {
    mode?: 'login' | 'register' | 'forgot'
    userType?: 'client' | 'agent'
}

const props = withDefaults(defineProps<LoginProps>(), {
    mode: 'login',
    userType: 'client'
})

const emit = defineEmits<{
    submit: [data: LoginFormData]
    'switch-mode': [mode: 'login' | 'register' | 'forgot']
}>()

const loading = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const codeCountdown = ref(0)
const codeTimer = ref<number>()

const formData = reactive<LoginFormData>({
    phone: '',
    code: '',
    password: '',
    confirmPassword: '',
    referrerPhone: ''
})

const errors = reactive({
    phone: '',
    code: '',
    password: '',
    confirmPassword: ''
})

const codeDisabled = computed(() => {
    return codeCountdown.value > 0 || !formData.phone || !validatePhoneFormat(formData.phone)
})

const codeText = computed(() => {
    return codeCountdown.value > 0 ? `${codeCountdown.value}s后重发` : '发送验证码'
})

const validatePhoneFormat = (phone: string) => {
    return /^1[3-9]\d{9}$/.test(phone)
}

const validatePhone = () => {
    if (!formData.phone) {
        errors.phone = '请输入手机号'
    } else if (!validatePhoneFormat(formData.phone)) {
        errors.phone = '请输入正确的手机号'
    } else {
        errors.phone = ''
    }
}

const validateForm = () => {
    let isValid = true

    // 验证手机号
    validatePhone()
    if (errors.phone) isValid = false

    // 验证验证码 (注册和忘记密码时)
    if (props.mode !== 'login') {
        if (!formData.code) {
            errors.code = '请输入验证码'
            isValid = false
        } else {
            errors.code = ''
        }
    }

    // 验证密码
    if (!formData.password) {
        errors.password = '请输入密码'
        isValid = false
    } else if (formData.password.length < 6) {
        errors.password = '密码长度不能少于6位'
        isValid = false
    } else {
        errors.password = ''
    }

    // 验证确认密码 (注册和忘记密码时)
    if (props.mode !== 'login') {
        if (!formData.confirmPassword) {
            errors.confirmPassword = '请确认密码'
            isValid = false
        } else if (formData.password !== formData.confirmPassword) {
            errors.confirmPassword = '两次输入的密码不一致'
            isValid = false
        } else {
            errors.confirmPassword = ''
        }
    }

    return isValid
}

const sendCode = async () => {
    if (codeDisabled.value) return

    try {
        await sendCodeApi({ phone: formData.phone })
        uni.showToast({ title: '验证码已发送', icon: 'none' })

        // 开始倒计时
        codeCountdown.value = 60
        codeTimer.value = setInterval(() => {
            codeCountdown.value--
            if (codeCountdown.value <= 0) {
                clearInterval(codeTimer.value)
            }
        }, 1000)
    } catch (error) {
        uni.showToast({ title: '验证码发送失败', icon: 'none' })
    }
}

const handleSubmit = () => {
    if (loading.value || !validateForm()) return

    loading.value = true
    emit('submit', { ...formData })

    // 重置loading状态 (由父组件控制)
    setTimeout(() => {
        loading.value = false
    }, 3000)
}

const getSubtitle = () => {
    switch (props.mode) {
        case 'login':
            return '请输入您的账号密码'
        case 'register':
            return '创建您的新账号'
        case 'forgot':
            return '重置您的登录密码'
        default:
            return ''
    }
}

const getButtonText = () => {
    switch (props.mode) {
        case 'login':
            return '登录'
        case 'register':
            return '注册'
        case 'forgot':
            return '重置密码'
        default:
            return '提交'
    }
}

// 清理定时器
onUnmounted(() => {
    if (codeTimer.value) {
        clearInterval(codeTimer.value)
    }
})

defineExpose({
    resetForm: () => {
        Object.assign(formData, {
            phone: '',
            code: '',
            password: '',
            confirmPassword: '',
            referrerPhone: ''
        })
        Object.assign(errors, {
            phone: '',
            code: '',
            password: '',
            confirmPassword: ''
        })
    },
    setLoading: (value: boolean) => {
        loading.value = value
    }
})
</script>

<style lang="scss" scoped>
.login-form {
    padding: 40rpx;

    .form-header {
        text-align: center;
        margin-bottom: 60rpx;

        .title {
            font-size: 48rpx;
            font-weight: bold;
            color: var(--theme-text-primary, #333);
            margin-bottom: 16rpx;
        }

        .subtitle {
            font-size: 28rpx;
            color: var(--theme-text-secondary, #666);
        }
    }

    .form-content {
        .input-group {
            margin-bottom: 40rpx;

            .input-label {
                font-size: 28rpx;
                color: #333;
                margin-bottom: 16rpx;
            }

            .input-wrapper {
                display: flex;
                align-items: center;
                padding: 24rpx 32rpx;
                border: 2rpx solid #e4e7ed;
                border-radius: 12rpx;
                background-color: #fff;

                &:focus-within {
                    border-color: #409eff;
                }

                input {
                    flex: 1;
                    font-size: 30rpx;
                    color: var(--theme-text-primary, #333);

                    &::placeholder {
                        color: var(--theme-text-tertiary, #c0c4cc);
                    }
                }

                .code-btn {
                    padding: 12rpx 24rpx;
                    background-color: #409eff;
                    color: #fff;
                    font-size: 24rpx;
                    border-radius: 8rpx;

                    &.disabled {
                        background-color: #c0c4cc;
                        color: #fff;
                    }
                }
            }

            .error-text {
                font-size: 24rpx;
                color: #f56c6c;
                margin-top: 8rpx;
            }
        }

        .submit-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            padding: 32rpx;
            background-color: #409eff;
            color: #fff;
            font-size: 32rpx;
            font-weight: bold;
            border-radius: 12rpx;
            margin: 60rpx 0 40rpx;

            &.disabled {
                background-color: #c0c4cc;
            }

            text {
                margin-left: 16rpx;
            }
        }

        .mode-switch {
            display: flex;
            justify-content: space-between;

            text {
                font-size: 26rpx;
                color: #409eff;
            }
        }
    }
}
</style>
